package com.learn.pager;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;

import com.learn.pager.fragment.ChatFragment;
import com.learn.pager.fragment.ContactFragment;
import com.learn.pager.fragment.FindFragment;

import java.util.ArrayList;
import java.util.List;

public class FragmentViewPagerActivity extends AppCompatActivity {

    private ViewPager pager;
    private List<Fragment> list;

    private TextView chatTv;
    private TextView findTv;
    private TextView contactTv;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_custom_view_pager);

        chatTv = findViewById(R.id.tv1);
        chatTv.setOnClickListener(new ViewPagerClickListener(0));

        findTv = findViewById(R.id.tv2);
        findTv.setOnClickListener(new ViewPagerClickListener(1));

        contactTv = findViewById(R.id.tv3);
        contactTv.setOnClickListener(new ViewPagerClickListener(2));

        list = new ArrayList<Fragment>();
        list.add(new ChatFragment());
        list.add(new FindFragment());
        list.add(new ContactFragment());
        pager = (ViewPager) findViewById(R.id.pager);
        MyAdapter adapter = new MyAdapter(getSupportFragmentManager());
        pager.setAdapter(adapter);
    }

    //处理Fragment和ViewPager的适配器
    private class MyAdapter extends FragmentPagerAdapter {

        public MyAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int arg0) {
            return list.get(arg0);
        }

        @Override
        public int getCount() {
            return list.size();
        }

    }

    private class ViewPagerClickListener implements View.OnClickListener {

        private int index;

        public ViewPagerClickListener(int index) {
            this.index = index;
        }

        @Override
        public void onClick(View v) {
            //改变ViewPager当前显示页面
            pager.setCurrentItem(index);
        }
    }
}
